﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;

namespace APMAWebConsole.PlanningPart
{
    public partial class UserStories : System.Web.UI.Page
    {
        private const string UserStoriesDataSourceKey = "UserStoriesDataSourceKey";
        private const string UsersListKey = "UsersListKey";
        private const string ProjectsListKey = "ProjectsListKey";
        private const string IterationsListKey = "IterationsListKey";
        private const string IsEditModeKey = "IsEditModeKey";
        private const string IsViewModeKey = "IsViewModeKey";
        private const string IsUpdateKey = "IsUpdateKey";
        private const string TasksListKey = "TasksListKey";

        public DataTable DataSource
        {
            get
            {
                return ViewState[UserStoriesDataSourceKey] != null
                           ? (DataTable)ViewState[UserStoriesDataSourceKey]
                           : (DataTable)(ViewState[UserStoriesDataSourceKey] = SiteMaster.Proxy.GetUserStoriesList());
            }

            set { ViewState[UserStoriesDataSourceKey] = value; }
        }

        public DataTable UsersList
        {
            get
            {
                return ViewState[UsersListKey] != null
                           ? (DataTable)ViewState[UsersListKey]
                           : (DataTable)(ViewState[UsersListKey] = SiteMaster.Proxy.GetUsersList());
            }

            set { ViewState[UsersListKey] = value; }
        }

        public DataTable ProjectsList
        {
            get
            {
                return ViewState[ProjectsListKey] != null
                           ? (DataTable)ViewState[ProjectsListKey]
                           : (DataTable)(ViewState[ProjectsListKey] = SiteMaster.Proxy.GetProjectsList());
            }

            set { ViewState[ProjectsListKey] = value; }
        }

        public DataTable IterationsList
        {
            get
            {
                return ViewState[IterationsListKey] != null
                           ? (DataTable)ViewState[IterationsListKey]
                           : (DataTable)(ViewState[IterationsListKey] = SiteMaster.Proxy.GetIterationsList());
            }

            set { ViewState[IterationsListKey] = value; }
        }

        private DataTable TasksList
        {
            get
            {
                if(ViewState[TasksListKey] != null)
                    return (DataTable) ViewState[TasksListKey];

                var table = SiteMaster.Proxy.GetTasksList();

                var expression = "User_story_id <> " + DataSource.Rows[SelectedRow]["Id"];

                var foundRows = table.Select(expression);
                
                foreach(var dataRow in foundRows)
                    table.Rows.Remove(dataRow);

                ViewState[TasksListKey] = table;

                return (DataTable)ViewState[TasksListKey];
            }

            set { ViewState[TasksListKey] = value; }
        }

        public bool IsEditMode
        {
            set { ViewState[IsEditModeKey] = value; }
            get { return ViewState[IsEditModeKey] != null && (bool) ViewState[IsEditModeKey]; }
        }

        public bool IsViewMode
        {
            set { ViewState[IsViewModeKey] = value; }
            get { return ViewState[IsViewModeKey] != null && (bool)ViewState[IsViewModeKey]; }
        }

        public bool IsUpdate
        {
            set { ViewState[IsUpdateKey] = value; }
            get { return ViewState[IsUpdateKey] != null && (bool)ViewState[IsUpdateKey]; }
        }

        private int SelectedRow
        {
            get
            {
                int selectedRow;
                var isSuccessfully = int.TryParse(txtSelectedUserStory.Text, out selectedRow);

                if (isSuccessfully && selectedRow - 1 >= 0 && selectedRow - 1 < DataSource.Rows.Count 
                        && DataSource.Rows[selectedRow - 1] != null)
                    return selectedRow - 1;

                return -1;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.User.Identity.IsAuthenticated)
                Response.Redirect("~/Account/Login.aspx");
        }

        private void Rebind()
        {
            if (IsEditMode)
            {
                txtUserStoryId.Enabled = false;

                txtUserStoryName.Enabled = ddlUserStoryOwnerId.Enabled = ddlUserStoryProjectId.Enabled =
                                                                         txtUserStoryDescription.Enabled =
                                                                         ddlUserStoryStateId.Enabled =
                                                                         txtUserStoryEstimate.Enabled =
                                                                         txtUserStoryActuals.Enabled =
                                                                         txtUserStoryToDo.Enabled =
                                                                         txtUserStoryPlanEstimate.Enabled =
                                                                         ddlUserStoryIterationId.Enabled =
                                                                         txtUserStoryNotes.Enabled =
                                                                         btnCreateUpdate.Visible = !IsViewMode;
                    

                ddlUserStoryOwnerId.Items.Clear();
                ddlUserStoryOwnerId.DataValueField = "Id";
                ddlUserStoryOwnerId.DataTextField = "Name";
                ddlUserStoryOwnerId.DataSource = UsersList;
                ddlUserStoryOwnerId.DataBind();
                ddlUserStoryOwnerId.Items.Insert(0, new ListItem(String.Empty, String.Empty));

                ddlUserStoryProjectId.Items.Clear();
                ddlUserStoryProjectId.DataValueField = "Id";
                ddlUserStoryProjectId.DataTextField = "Name";
                ddlUserStoryProjectId.DataSource = ProjectsList;
                ddlUserStoryProjectId.DataBind();
                ddlUserStoryProjectId.Items.Insert(0, new ListItem(String.Empty, String.Empty));

                ddlUserStoryIterationId.Items.Clear();
                ddlUserStoryIterationId.DataValueField = "Id";
                ddlUserStoryIterationId.DataTextField = "Id";
                ddlUserStoryIterationId.DataSource = IterationsList;
                ddlUserStoryIterationId.DataBind();
                ddlUserStoryIterationId.Items.Insert(0, new ListItem(String.Empty, String.Empty));

                ddlUserStoryStateId.Items.Clear();
                ddlUserStoryStateId.DataValueField = "Id";
                ddlUserStoryStateId.DataTextField = "Name";
                ddlUserStoryStateId.Items.Insert(0, new ListItem(String.Empty, String.Empty));
                ddlUserStoryStateId.Items.Insert(1, new ListItem("Defined", "1"));
                ddlUserStoryStateId.Items.Insert(2, new ListItem("Completed", "2"));
                ddlUserStoryStateId.Items.Insert(3, new ListItem("In progress", "3"));

                if (!IsUpdate)
                {
                    txtUserStoryId.Text = txtUserStoryName.Text = txtUserStoryDescription.Text = txtUserStoryEstimate.Text =
                                                                              txtUserStoryActuals.Text =
                                                                              txtUserStoryToDo.Text =
                                                                              txtUserStoryPlanEstimate.Text =
                                                                              txtUserStoryNotes.Text = "";
                    ddlUserStoryOwnerId.SelectedIndex = 0;
                    ddlUserStoryProjectId.SelectedIndex = 0;
                    ddlUserStoryIterationId.SelectedIndex = 0;
                    ddlUserStoryStateId.SelectedIndex = 0;
                }
                else
                {
                    var selectedRow = SelectedRow;

                    if (selectedRow == -1)
                        return;

                    txtUserStoryId.Text = DataSource.Rows[selectedRow]["Id"].ToString();
                    txtUserStoryName.Text = DataSource.Rows[selectedRow]["Name"].ToString();
                    txtUserStoryDescription.Text = DataSource.Rows[selectedRow]["Description"].ToString();
                    txtUserStoryEstimate.Text = DataSource.Rows[selectedRow]["Estimate"].ToString();
                    txtUserStoryActuals.Text = DataSource.Rows[selectedRow]["Actuals"].ToString();
                    txtUserStoryToDo.Text = DataSource.Rows[selectedRow]["To_do"].ToString();
                    txtUserStoryPlanEstimate.Text = DataSource.Rows[selectedRow]["Plan_estimate"].ToString();
                    txtUserStoryNotes.Text = DataSource.Rows[selectedRow]["Notes"].ToString();

                    ddlUserStoryOwnerId.SelectedValue = DataSource.Rows[selectedRow]["Owner_id"].ToString() != ""
                                                            ? DataSource.Rows[selectedRow]["Owner_id"].ToString()
                                                            : null;

                    ddlUserStoryProjectId.SelectedValue = DataSource.Rows[selectedRow]["Project_id"].ToString() != ""
                                                            ? DataSource.Rows[selectedRow]["Project_id"].ToString()
                                                            : null;

                    ddlUserStoryIterationId.SelectedValue = DataSource.Rows[selectedRow]["Iteration_id"].ToString() != ""
                                                            ? DataSource.Rows[selectedRow]["Iteration_id"].ToString()
                                                            : null;

                    ddlUserStoryStateId.SelectedValue = DataSource.Rows[selectedRow]["State_id"].ToString() != ""
                                                            ? DataSource.Rows[selectedRow]["State_id"].ToString()
                                                            : null;


                    grdTasks.Visible = IsViewMode;
                    if (IsViewMode)
                    {
                        grdTasks.DataSource = TasksList;
                        grdTasks.DataBind();
                    }
                }
            }
            else
            {
                grdUserStories.DataSource = DataSource;
                grdUserStories.DataBind();
            }
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            divEditMode.Visible = IsEditMode;
            divUserStoriesGrid.Visible = !IsEditMode;

            btnAddUserStory.Visible = !IsEditMode;
            btnEditUserStory.Visible =
                btnRemoveUserStory.Visible = btnViewUserStory.Visible = false;
            btnBackToList.Visible = IsEditMode;

            if (IsEditMode)
            {
                btnCreateUpdate.Text = IsUpdate ? "Update" : "Create";
            }

            Rebind();
        }

        protected void OnButtonCommand(object sender, CommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "Add":
                    {
                        IsEditMode = true;
                        IsUpdate = false;
                        IsViewMode = false;

                        break;
                    }
                case "Remove":
                    {
                        if (e.CommandArgument.ToString() != "")
                            txtSelectedUserStory.Text = e.CommandArgument.ToString();

                        RemoveUserStory();

                        break;
                    }
                case "Edit":
                    {
                        IsEditMode = true;
                        IsUpdate = true;
                        IsViewMode = false;

                        break;
                    }

                case "Select":
                    {
                        txtSelectedUserStory.Text = e.CommandArgument.ToString();
                        IsEditMode = true;
                        IsUpdate = true;
                        IsViewMode = false;

                        break;
                    }

                case "View":
                    {
                        if (e.CommandArgument.ToString() != "")
                            txtSelectedUserStory.Text = e.CommandArgument.ToString();

                        IsEditMode = true;
                        IsUpdate = true;
                        IsViewMode = true;
                        TasksList = null;

                        break;
                    }

                case "SaveUpdate":
                    {
                        if (IsEditMode)
                        {
                            if (IsUpdate)
                            {
                                UpdateUserStory();
                            }
                            else
                            {
                                SaveUserStory();
                            }
                        }

                        break;
                    }

                case "BackToList":
                    {
                        IsEditMode = false;
                        TasksList = null;

                        break;
                    }
            }
        }

        private Dictionary<string, object> PrepareParameters(Dictionary<string, object> parameters)
        {
            parameters.Add("Name", txtUserStoryName.Text);

            int intParseValue;

            var isParsed = int.TryParse(ddlUserStoryOwnerId.SelectedValue, out intParseValue);
            parameters.Add("Owner_id", isParsed ? (int?)intParseValue : null);

            isParsed = int.TryParse(ddlUserStoryProjectId.SelectedValue, out intParseValue);
            parameters.Add("Project_id", isParsed ? (int?)intParseValue : null);

            parameters.Add("Description", txtUserStoryDescription.Text);

            isParsed = int.TryParse(ddlUserStoryStateId.SelectedValue, out intParseValue);
            parameters.Add("State_id", isParsed ? (int?)intParseValue : null);

            isParsed = int.TryParse(txtUserStoryEstimate.Text, out intParseValue);
            parameters.Add("Estimate", isParsed ? (int?)intParseValue : null);

            isParsed = int.TryParse(txtUserStoryActuals.Text, out intParseValue);
            parameters.Add("Actuals", isParsed ? (int?)intParseValue : null);

            isParsed = int.TryParse(txtUserStoryToDo.Text, out intParseValue);
            parameters.Add("To_do", isParsed ? (int?)intParseValue : null);

            isParsed = int.TryParse(txtUserStoryPlanEstimate.Text, out intParseValue);
            parameters.Add("Plan_estimate", isParsed ? (int?)intParseValue : null);

            isParsed = int.TryParse(ddlUserStoryIterationId.SelectedValue, out intParseValue);
            parameters.Add("Iteration_id", isParsed ? (int?)intParseValue : null);

            parameters.Add("Notes", txtUserStoryNotes.Text);

            return parameters;
        }

        private bool ValidateFields()
        {
            return Page.IsValid;
        }

        private void SaveUserStory()
        {
            if (!ValidateFields())
                return;

            var parameters = PrepareParameters(new Dictionary<string, object>());

            SiteMaster.Proxy.AddNewUserStory(parameters, Page.User.Identity.Name);

            IsEditMode = false;
            DataSource = null;
        }

        private void UpdateUserStory()
        {
            if (!ValidateFields())
                return;

            var parameters = new Dictionary<string, object>();

            int intParseValue;
            var isParsed = int.TryParse(txtUserStoryId.Text, out intParseValue);

            if (!isParsed)
                return;

            parameters.Add("Id", intParseValue);

            parameters = PrepareParameters(parameters);

            SiteMaster.Proxy.UpdateUserStory(parameters, Page.User.Identity.Name);

            IsEditMode = false;
            DataSource = null;
        }

        private void RemoveUserStory()
        {
            var selectedRow = SelectedRow;

            if (selectedRow == -1)
                return;

            int intParseValue;
            var isParsed = int.TryParse(DataSource.Rows[selectedRow]["Id"].ToString(), out intParseValue);

            if (!isParsed)
                return;

            SiteMaster.Proxy.RemoveUserStory(intParseValue, Page.User.Identity.Name);

            IsEditMode = false;
            DataSource = null;
        }
    }
}